﻿using SqlDao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace clf.code.first
{
    internal class BaseHadnle
    {

        protected DbHelper instance;
        protected string connectStr;
        /// <summary>
        /// 数据库存名称
        /// </summary>
        protected string databaseName;
        protected List<DbSchema> mTables;


        protected void Notify(Action<ProgressResult> callback, int progress, string msg)
        {
            var result = new ProgressResult() { Progess = progress, Message = msg };
            callback?.Invoke(result);
        }

        protected bool IsTypeInTables(Type type)
        {
            return mTables.Any((table) =>
            {
                return table.TableName.Equals(Helper.CamelCaseToDBnameing(type.Name));
            });
        }


        /// <summary>
        /// sort by name and id remove to first
        /// </summary>
        /// <param name="fields"></param>
        protected void SortByName(List<FieldInfo> fields)
        {
            fields?.Sort((f1, f2) => { return StringComparer.OrdinalIgnoreCase.Compare(f1.Name, f2.Name); });

            var idf = fields?.Find((f) => { return f.Name == "id" || f.Name.Equals("Id"); });
            if (idf != null)
            {
                fields.Remove(idf);
                fields.Insert(0, idf);
            }
        }

        /// <summary>
        ///清除 空行 和注解
        /// </summary>
        /// <param name="sb"></param>
        /// <returns></returns>
        protected StringBuilder RemoveEmptyLines(StringBuilder sb)
        {
            StringBuilder result = new StringBuilder();

            string[] lines = sb.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            foreach (string line in lines)
            {
                // 使用String.IsNullOrWhiteSpace来检查行是否为空 和注解
                if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith("-- "))
                {
                    result.AppendLine(line);
                }
            }
            return result;
        }

        protected int Excute(string sqls)
        {
            return instance.ExecuteNonQuery(sqls);
        }
    }
}
